package com.cljz.peipei.present.activity;

import com.cljz.peipei.base.App;
import com.cljz.peipei.base.BaseP;
import com.cljz.peipei.base.Constant;
import com.cljz.peipei.model.net.api.Api;
import com.cljz.peipei.model.net.bean.ThirdLoginBean;
import com.cljz.peipei.model.net.bean.UserSetBean;
import com.cljz.peipei.ui.activity.SetNicknameActivity;
import com.clzj.peipei.bean.UserInfo;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.net.ApiSubcriber;
import cn.droidlover.xdroidmvp.net.NetError;
import cn.droidlover.xdroidmvp.net.XApi;

/**用户设置
 * Created by apple on 2017/4/18.
 */

public class SetUserP extends BaseP<SetNicknameActivity> {
    private String beforeToken;

    public void userSet(final String sex, final String age, final String nickname, final String constellation) {
        beforeToken = getToken();
        Api.getResponseInfoAPI().userSetData(beforeToken, nickname, sex, age,constellation)
                .compose(XApi.<UserSetBean>getApiTransformer())
                .compose(XApi.<UserSetBean>getScheduler())
                .compose(getV().<UserSetBean>bindToLifecycle())
                .subscribe(new ApiSubcriber<UserSetBean>() {
                    @Override
                    protected void onFail(NetError error) {

                    }

                    @Override
                    public void onNext(UserSetBean userSetBean) {
                        if ("0".equals(userSetBean.getCode())) {
                            getV().setUserSucceed(userSetBean);
                            intoDB(userSetBean.getData().get(0), nickname, sex, age,constellation);
                        } else if ("1000".equals(userSetBean.getCode())) {
                            getV().loginOvertime(1);
                        } else {
                            getV().setUserFail(userSetBean.getMsg());
                        }
                    }
                });
    }
    private void intoDB(String token, String nickname, String sex, String age,String constellation) {
        SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, token);
        UserInfo userInfo = getUserInfo(beforeToken);
        daoSession.getUserInfoDao().delete(userInfo);
        userInfo.setToken(token);
        userInfo.setNickname(nickname);
        userInfo.setBirthday(age);
        userInfo.setSex(sex);
        userInfo.setConstellation(constellation);
        daoSession.getUserInfoDao().insert(userInfo);
    }
}
